/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SalesInvoice.java
 *
 * Created on Nov 9, 2010, 8:23:16 AM
 */

package lmclogistics;

import components.Text;
import components.TextArea;
import components.Image;
import components.NButton;
import components.Dates;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.print.PrinterException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import org.joda.time.DateTime;
import org.joda.time.Days;
import sql.Sql;

/**
 *
 * @author Sonia Tan
 */
public class SalesInvoice extends javax.swing.JPanel {

    /** Creates new form EirinPanel */    
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    static ArrayList out;

    private Image bg;
    private static JTable siTable;
    private JScrollPane scroll;
    public static DefaultTableModel model;
    private static TableColumn column;

    NButton selectEIR;
    static Text totalVal = new Text();
    static float totalAmt;
    static float total;
    static int customer;

    static TextArea invoiceNoField= new TextArea();
    static JComboBox customerField = new JComboBox();
    static TextArea discountField = new TextArea();
         JTextArea remarksField = new JTextArea();
         TextArea poNoField = new TextArea();
    static TextArea vatField = new TextArea();
    Dates dateVal = new Dates();

    public SalesInvoice() {
        total=0;
        totalAmt=0;
        out=new ArrayList();
        initComponents();
        setOpaque(false);
        setLocation(getCenterX(507), getCenterY(460));
        setSize(507, 460);
        setVisible(true);
        setBg();
        initText();
        initInput();
        select();
        initTable();
        showTable();
    }

    public void select()
    {
        selectEIR.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent e) {
                    total = 0;
                    customer = getCustCode();
                    SelectEIR se = new SelectEIR(customerField.getSelectedItem().toString(),1);
                    }
                });
    }

    public int getCustCode()
    {
        String query = "SELECT custCode FROM customer WHERE custName='" + customerField.getSelectedItem().toString() + "'";

        try {
            Connection connection = Sql.getSqlConnection();
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            if(rs.next())
            {
                return Integer.parseInt(rs.getString(1));
            }

            Sql.closeSqlConnection(connection);
        } catch (Exception ex) {
            Logger.getLogger(SelectEIR.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }

    public static void setValues(ArrayList outCode) throws Exception
    {
        showTable();
        out = outCode;

         try {
            Connection connection = Sql.getSqlConnection();
            Statement stmt = connection.createStatement();
            
            for(int i=0; i<outCode.size(); i++)
            {
                String query = "SELECT rate FROM rate WHERE chsSize="
                 + "(SELECT chsSize FROM chassis WHERE chsPin="
                 + "(SELECT chsCode FROM rental WHERE outCode =" + outCode.get(i) + ") "
                 + "AND custCode='"+customer+"')";
                        
                ResultSet rs = stmt.executeQuery(query);

                while(rs.next())
                {
                    Vector rowData = new Vector();
                    int r = Integer.parseInt(rs.getString(1));
                    int days = getDates(Integer.parseInt(outCode.get(i).toString()));
                    int amt = r*days;
                    float disc = 1 - Float.parseFloat(discountField.getText())/100 ;
                    System.out.println(disc);
                    float vat = Float.parseFloat(vatField.getText())/100 + 1;
                    System.out.println(vat);
                    totalAmt = totalAmt+amt;
                    total = totalAmt*vat*disc;

                    rowData.add(outCode.get(i));
                    rowData.add(days);
                    rowData.add(r);
                    rowData.add(amt);
                    model.addRow(rowData);
                }

                totalVal.inText(""+total,320,350);

                siTable.setModel(model);

                column = siTable.getColumnModel().getColumn(0);
                column.setPreferredWidth(125);

                column = siTable.getColumnModel().getColumn(1);
                column.setPreferredWidth(125);

                column = siTable.getColumnModel().getColumn(2);
                column.setPreferredWidth(125);

                column = siTable.getColumnModel().getColumn(3);
                column.setPreferredWidth(125);
            }
            Sql.closeSqlConnection(connection);
        } catch (SQLException ex) {
            Logger.getLogger(SalesInvoice.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

    public static int getDates(int outCode)
    {
        String query = "SELECT outDate, inDate FROM rental WHERE outCode =" + outCode;

        try {
            Connection connection = Sql.getSqlConnection();
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            if(rs.next())
            {
                return nDays(rs.getString(1),rs.getString(2));
            }

        } catch (Exception ex) {
            Logger.getLogger(SalesInvoice.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }

    public static int nDays(String frDate,String toDate) {

        String[] dateT = splitDate(toDate);
        String[] dateG = splitDate(frDate);

        int tYear = Integer.parseInt(dateT[0]);
        int tMonth = Integer.parseInt(dateT[1]);
        int tDay = Integer.parseInt(dateT[2]);
        int gYear = Integer.parseInt(dateG[0]);
        int gMonth = Integer.parseInt(dateG[1]);
        int gDay = Integer.parseInt(dateG[2]);

        DateTime start = new DateTime(gYear, gMonth, gDay, 0, 0, 0, 0);
        DateTime end = new DateTime(tYear, tMonth, tDay, 0, 0, 0, 0);

        Days d = Days.daysBetween(start,end);
        int days = d.getDays();
        
        return days;

    }

    public static String[] splitDate(String date){
        String[] dateT = date.split("-");

        return dateT;
    }

    public void initText(){

         Text time = new Text();
         Text invoiceNo= new Text();
         Text date = new Text();         
         Text customer = new Text();
         Text discount = new Text();
         Text total = new Text();         
         Text remarks = new Text();
         Text poNo = new Text();
         Text vat = new Text();

        Calendar cal = new GregorianCalendar();
        int hour = cal.get(Calendar.HOUR);
        int minute = cal.get(Calendar.MINUTE);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String curDate = dateFormat.format(calendar.getTime());
        dateVal.setDate(curDate);
        
        time.inText(hour+":"+minute,15,15);
        invoiceNo.inText("INV NO:",15,40);
        date.inText("DATE:",200,40);
        dateVal.setLocation(250,38);
        customer.inText("TO:",15,65);
        discount.inText("Discount:", 250, 300);
        vat.inText("VAT:", 250, 325);
        total.inText("TOTAL:",250,350);
        totalVal.inText("",320,350);
        poNo.inText("PO No.:", 15, 300);
        remarks.inText("Remarks:",15, 325);
        selectEIR = new NButton("Select rental record",200,63);
        selectEIR.setSize(150,25);

        add(time,0);
        add(invoiceNo,0);
        add(date,0);
        add(dateVal,0);
        add(customer,0);
        add(discount,0);
        add(total,0);
        add(totalVal,0);
        add(remarks,0);
        add(poNo,0);
        add(vat,0);
        add(vat,0);
        add(remarks,0);
        add(selectEIR,1);
    }

    public final void setBg(){
        bg = new Image("panel.png",507,460);

        add(bg,-1);

    }

    public int getCenterX(int x){

        int a = 919/2 - x/2;


        return a;
    }

    public int getCenterY(int x){

        int a = 577/2 - x/2;


        return a;
    }

    public void initInput(){        
        popCombo();

         //date.initDates(350, 25, 250, 38);
         invoiceNoField.initText(94,25,75,38);
         discountField.initText(80,25,320,298);
         poNoField.initText(80,25,70,298);
         vatField.initText(80,25,320,323);
         remarksField.setSize(230, 70);
         remarksField.setLocation(15, 350);
         customerField.setSize(125,25);
         customerField.setLocation(75,63);

         discountField.setText(""+0);
         vatField.setText(""+12);

         discountField.addKeyListener(new KeyListener() {

            public void keyTyped(KeyEvent ke) {                        
            }

            public void keyPressed(KeyEvent ke) {
            }

            public void keyReleased(KeyEvent ke) {
                if(discountField.getText().equals(""))
                        {
                            discountField.setText("0");
                            float disc = 1 - Float.parseFloat(discountField.getText())/100;
                            float vat = Float.parseFloat(vatField.getText())/100 + 1;
                            total = totalAmt*vat*disc;
                            totalVal.inText(""+total,320,350);
                        }
                        else
                        {
                            float disc = 1 - Float.parseFloat(discountField.getText())/100;
                            float vat = Float.parseFloat(vatField.getText())/100 + 1;
                            total = totalAmt*vat*disc;
                            totalVal.inText(""+total,320,350);
                        }
            }

         });

        vatField.addKeyListener(new KeyListener() {

            public void keyTyped(KeyEvent ke) {                        
            }

            public void keyPressed(KeyEvent ke) {
            }

            public void keyReleased(KeyEvent ke) {
                if(vatField.getText().equals(""))
                        {
                            vatField.setText("0");
                            float disc = 1 - Float.parseFloat(discountField.getText())/100;
                            float vat = Float.parseFloat(vatField.getText())/100 + 1;
                            total = totalAmt*vat*disc;
                            totalVal.inText(""+total,320,350);
                        }
                        else
                        {
                            float disc = 1 - Float.parseFloat(discountField.getText())/100;
                            float vat = Float.parseFloat(vatField.getText())/100 + 1;
                            total = totalAmt*vat*disc;
                            totalVal.inText(""+total,320,350);
                        }
            }

         });

         add(invoiceNoField,0);
         add(customerField,0);
         add(discountField,0);
         add(remarksField,0);
         add(poNoField,0);
         add(vatField,0);
    }

    public static int acceptInvoice() throws PrinterException
    {
        if(invoiceNoField.getText().equals(""))
        {
            FormWarning fw = new FormWarning("incomplete");
            return 0;
        }
        else
        {
            try {
                Connection connection = Sql.getSqlConnection();
                for (int i = 0; i < out.size(); i++) {
                    String query = "UPDATE rental SET paid=1 WHERE outCode="+out.get(i);

                    PreparedStatement pstmt = connection.prepareStatement(query);
                    pstmt.executeUpdate();
                }
                Sql.closeSqlConnection(connection);

                siTable.print();
                return 1;
            } catch (Exception ex) {
                Logger.getLogger(SalesInvoice.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return 0;
    }

    public void popCombo()
    {
        customerField.removeAllItems();

        String custQuery = "SELECT custName FROM customer";

        try {
                Connection connection = Sql.getSqlConnection();
                Statement stmt = connection.createStatement();

                ResultSet rs = stmt.executeQuery(custQuery);
                customerField.insertItemAt("<Customer>", 0);
                customerField.setSelectedIndex(0);
                int i = 1;
                while(rs.next())
                {
                    customerField.insertItemAt(rs.getString(1),i);
                    i++;
                }
                Sql.closeSqlConnection(connection);
        } catch (Exception ex) {
                Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void initTable(){
                siTable = new JTable(model);
		siTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		siTable.setFont(new Font("Lucida Grande", Font.PLAIN, 12));
		siTable.getTableHeader().setFont(new Font("Lucida Grande", Font.PLAIN, 12));
		scroll = new JScrollPane(siTable);
		scroll.setBounds(15,88,477,200);
		add(scroll,0);
                siTable.setAutoCreateRowSorter(true);

    }

    public static void showTable()
    {
           model = new DefaultTableModel(){
			    public boolean isCellEditable(int row, int column) {
			    	return false;
				}
                            };
            model.addColumn("EIR NO");
            model.addColumn("Days");
            model.addColumn("Rate");
            model.addColumn("Amount");

            siTable.setModel(model);

            column = siTable.getColumnModel().getColumn(0);
            column.setPreferredWidth(125);

            column = siTable.getColumnModel().getColumn(1);
            column.setPreferredWidth(125);

            column = siTable.getColumnModel().getColumn(2);
            column.setPreferredWidth(125);

            column = siTable.getColumnModel().getColumn(3);
            column.setPreferredWidth(125);

            

    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

}
